package com.systemframework.util;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.systemframework.exception.ResultException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * @author summer
 * @date 2023-03-21 11:47
 */
@Slf4j
public class ExcelImport {

    public  <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            throw new ResultException("导入的文件路径不能为空");
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);

        try {
           return  ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (Exception e) {
            log.error("importExcel:{}",e.getMessage(),e);
            throw new ResultException(e.getMessage());

        }

    }
    public  <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            throw new ResultException("导入的文件不能为空");
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        try {
           return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            log.error("importExcel:{}",e.getMessage(),e);
            throw new ResultException(e.getMessage());
        }

    }
}
